package com.ht.module.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.constant.RedisConstant;
import com.ht.module.sys.entity.SysDict;
import com.ht.module.sys.entity.SysDictItem;
import com.ht.module.sys.mapper.SysDictItemMapper;
import com.ht.module.sys.mapper.SysDictMapper;
import com.ht.module.sys.service.SysDictItemService;
import com.ht.util.CommMethod;
import com.ht.util.Pager;
import com.ht.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典项表 服务实现类
 * </p>
 *
 * @author Auto-generator
 * @since 2021-05-19
 */
@Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysDictMapper sysDictMapper;

    @Override
    public List<SysDictItem> findList(SysDictItem en) {
        LambdaQueryWrapper<SysDictItem> query = Wrappers.<SysDictItem>lambdaQuery()
                .eq(StrUtil.isNotEmpty(en.getDictId()), SysDictItem::getDictId, en.getDictId())
                .eq(StrUtil.isNotEmpty(en.getValue()), SysDictItem::getValue, en.getValue())
                .eq(StrUtil.isNotEmpty(en.getLabel()), SysDictItem::getLabel, en.getLabel())
                .orderByAsc(SysDictItem::getSort);
        return baseMapper.selectList(query);
    }

    @Override
    public Pager<SysDictItem> findPage(Pager<SysDictItem> pager, SysDictItem en) {

        LambdaQueryWrapper<SysDictItem> query = Wrappers.<SysDictItem>lambdaQuery()
                .eq(StrUtil.isNotEmpty(en.getDictId()), SysDictItem::getDictId, en.getDictId())
                .eq(StrUtil.isNotEmpty(en.getValue()), SysDictItem::getValue, en.getValue())
                .eq(StrUtil.isNotEmpty(en.getLabel()), SysDictItem::getLabel, en.getLabel());

        return baseMapper.selectPage(pager, query);
    }

    @Override
    @Transactional
    public void delById(String id) {
        //删除字典项
        baseMapper.deleteById(id);
        //获取缓存中的数据
        Map<String, Object> map = (Map<String, Object>) redisUtil.get(RedisConstant.DICT_LIST);
        //删除缓存
        for (String key : map.keySet()) {
            List<SysDictItem> sysDictItems = JSON.parseArray(JSON.toJSONString(map.get(key))).toJavaList(SysDictItem.class);
            //移除
            map.put(key, sysDictItems.stream().filter(x -> !x.getId().equals(id)).toList());
        }
        //重新缓存
        redisUtil.set(RedisConstant.DICT_LIST, map);
    }

    @Override
    @Transactional
    public void add(SysDictItem sysDictItem) {
        CommMethod.beanCreate(sysDictItem);
        this.save(sysDictItem);
        //获取缓存中的数据
        Map<String, List<SysDictItem>> map = (Map<String, List<SysDictItem>>) redisUtil.get(RedisConstant.DICT_LIST);
        if (ObjectUtil.isEmpty(map)) {
            //全量缓存
            this.fullCacheRedis();
        } else {
            //查询出当前字典
            SysDict sysDict = sysDictMapper.selectById(sysDictItem.getDictId());
            //获取缓存中已有的字典值
            List<SysDictItem> sysDictItems = map.get(sysDict.getDictCode());
            if (ObjectUtil.isEmpty(sysDictItems)) {
                //第一次缓存
                map.put(sysDict.getDictCode(), new ArrayList<SysDictItem>() {{
                    add(sysDictItem);
                }});
            } else {
                //已有缓存
                map.get(sysDict.getDictCode()).add(sysDictItem);
            }
            //重新缓存
            redisUtil.set(RedisConstant.DICT_LIST, map);
        }


    }

    @Override
    @Transactional
    public void edit(SysDictItem sysDictItem) {
        CommMethod.beanUpdate(sysDictItem);
        this.updateById(sysDictItem);
        //获取缓存中的数据
        Map<String, Object> map = (Map<String, Object>) redisUtil.get(RedisConstant.DICT_LIST);
        //修改缓存
        for (String key : map.keySet()) {
            List<SysDictItem> sysDictItems = JSON.parseArray(JSON.toJSONString(map.get(key))).toJavaList(SysDictItem.class);
            for (int i = 0; i < sysDictItems.size(); i++) {
                SysDictItem temp = sysDictItems.get(i);
                if (temp.getId().equals(sysDictItem.getId())) {
                    //找到了
                    sysDictItems.set(i, sysDictItem);
                    map.put(key, sysDictItems);
                    break;
                }
            }
        }
        //重新缓存
        redisUtil.set(RedisConstant.DICT_LIST, map);
    }


    /**
     * 全量同步
     */
    @Override
    public void fullCacheRedis() {
        //如果map不存在在全量同步-查询出所有码表
        List<SysDict> sysDicts = sysDictMapper.selectList(new QueryWrapper<>());
        //查询出所有字典项
        List<SysDictItem> sysDictItems = this.findList(new SysDictItem());
        //定义缓存map对象
        Map<String, List<SysDictItem>> map = new HashMap<>();
        for (SysDict sysDict : sysDicts) {
            //遍历字典
            map.put(sysDict.getDictCode(), sysDictItems.stream().filter(x -> x.getDictId().equals(sysDict.getId())).toList());
        }
        //存入缓存
        redisUtil.set(RedisConstant.DICT_LIST, map);
    }

    /**
     * 全量同步并返回code的字典项
     */
    @Override
    public List<SysDictItem> fullCacheRedis(String code) {
        //如果map不存在在全量同步-查询出所有码表
        List<SysDict> sysDicts = sysDictMapper.selectList(new QueryWrapper<>());
        //查询出所有字典项
        List<SysDictItem> sysDictItems = this.findList(new SysDictItem());
        //定义缓存map对象
        Map<String, List<SysDictItem>> map = new HashMap<>();
        for (SysDict sysDict : sysDicts) {
            //遍历字典
            map.put(sysDict.getDictCode(), sysDictItems.stream().filter(x -> x.getDictId().equals(sysDict.getId())).toList());
        }
        //存入缓存
        redisUtil.set(RedisConstant.DICT_LIST, map);

        //找到当前编码的字典
        List<SysDict> temp = sysDicts.stream().filter(x -> x.getDictCode().equals(code)).toList();
        if (temp.isEmpty()) {
            return null;
        }
        return sysDictItems.stream().filter(x -> x.getDictId().equals(temp.get(0).getId())).collect(Collectors.toList());
    }

    /**
     * 按字典编码增量同步
     */
    @Override
    public List<SysDictItem> addCacheRedis(Map<String, List<SysDictItem>> map, String code) {
        //查询出码表的值
        List<SysDictItem> items = sysDictMapper.getItem(code);
        //判断码表是否存在
        if (!items.isEmpty()) {
            map.put(code, items);
            redisUtil.set(RedisConstant.DICT_LIST, map);
        }
        return items;
    }

}
